*** Calculate number of children for married household ***

do "E:\yungyu\lottery_baby\do\set_environment.do"

capture log close
log using "$log\1.1.childnum_couple.log" , replace
clear
set more off

use "$public\real_jhq.dta" , clear

keep if gender=="1" | gender=="2" //Keep only male and female
drop if born_year==. //drop children with unknown born year
drop if born_year>109 //drop children born after 2020 (ROC year 109)

drop if fr_idn=="" & mo_idn=="" //drop children with no parents information

gen baby = 1

replace born_year = 92 if born_year<=92 //children born before 2003 (ROC year 92)

collapse (sum)baby , by(fr_idn mo_idn gender born_year) //calculate total number of children each birth year by paried parents

replace gender = "boy"  if gender=="1"
replace gender = "girl" if gender=="2"

reshape wide baby, i(fr_idn mo_idn born_year) j(gender) string
reshape wide baby*, i(fr_idn mo_idn) j(born_year)
rename babyboy92 prebabyboy //children born before 2003 (ROC year 92)
rename babygirl92 prebabygirl

mvencode pre*baby*, mv(0) //recode missing as 0

collapse (sum)pre* (sum)baby* , by(fr_idn mo_idn)

keep fr_idn mo_idn pre* baby*
order fr_idn mo_idn pre* baby*

rename fr_idn male_idn
rename mo_idn female_idn

reshape long babyboy babygirl , i(male_idn female_idn pre*) j(year)

sort male_idn female_idn year

foreach x in "boy" "girl"{ //calculate culmulative number of children each year
	replace prebaby`x'=prebaby`x'[_n-1]+baby`x'[_n-1] if male_idn==male_idn[_n-1] & female_idn==female_idn[_n-1]
	gen totbaby`x'=prebaby`x'+baby`x'
}

save "$wdata\childnum_couple.dta" , replace

forv i = 93(1)109{ //Year 2004 to 2020
	use "$wdata\childnum_couple.dta" , clear
	keep if year == `i'
	save "$wdata\childnum_couple_`i'.dta" , replace
}

log close
